/**
 * Copyright (C) 2011 Taobao Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.taobao.jaket;

import java.util.HashMap;
import java.util.Map;

import junit.framework.Assert;

import org.junit.Test;

import com.google.gson.Gson;
import com.taobao.jaket.model.Address;
import com.taobao.jaket.model.Person;

/**
 * @author Xueqiang Mi
 */
public class JsonRendererTest_ObjectWithMap {
    @Test
    public void testToJson() {
        JsonRenderer renderer = new JsonRenderer();
        renderer.name("id").value(34780);
        renderer.name("name").value("yijiang");
        renderer.name("age").value(25);

        Map<Integer, Address> map = new HashMap<Integer, Address>();
        for (int i = 0; i < 3; i++) {
            Address address = new Address(310099 + i, "No.99, Huaxing Rd._" + i, "Hangzhou_" + i, "Zhejiang_" + i,
                    "CN_" + i);
            map.put(i, address);
        }
        renderer.name("addresses").value(map);
        String json = renderer.build();
        System.out.println(json);

        PersonWithMapAddress p = new Gson().fromJson(json, PersonWithMapAddress.class);
        Assert.assertNotNull(p);
        Assert.assertEquals(34780, p.getId());
        Assert.assertEquals("yijiang", p.getName());
        Assert.assertEquals(25, p.getAge());
        Assert.assertEquals(3, p.getAddresses().size());
        for (int i : p.getAddresses().keySet()) {
            Address address = p.getAddresses().get(i);
            Assert.assertNotNull(address);
            Assert.assertEquals(310099 + i, address.getZipCode());
            Assert.assertEquals("No.99, Huaxing Rd._" + i, address.getAddress());
            Assert.assertEquals("Hangzhou_" + i, address.getCity());
            Assert.assertEquals("Zhejiang_" + i, address.getProvince());
            Assert.assertEquals("CN_" + i, address.getCountry());
        }
    }
}

class PersonWithMapAddress extends Person {
    private Map<Integer, Address> addresses;

    public Map<Integer, Address> getAddresses() {
        if (addresses == null) {
            addresses = new HashMap<Integer, Address>();
        }
        return addresses;
    }

    public void setAddresses(Map<Integer, Address> addresses) {
        this.addresses = addresses;
    }
}